﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;

namespace Tulde.Windows.Amazon
{
    public static class AlbumArtService
    {
        public static AlbumArt Locate(AmazonCredentials credentials, string album, string artist)
        {
            SignedRequestHelper helper = new SignedRequestHelper(credentials);

            MusicServiceParameters parameters = new MusicServiceParameters
            {
                Album = album,
                Artist = artist,
                Operation = Operations.ItemSearch,
                SearchIndex = SearchIndex.Music,
                Service = ServiceNames.AWSECommerceService,
                ResponseGroup = ResponseGroup.Medium,
                Version = Settings.Version
               
            };
           

            WebRequest request = HttpWebRequest.Create(helper.Sign(parameters.ToString()));
            WebResponse response = request.GetResponse();
            XDocument doc = XDocument.Load(response.GetResponseStream());
            XNamespace ns = Settings.Namespace;


            return new AlbumArt
            {
                LargeUrl = ExtractUrl(doc, ns, Constants.LargeImage),
                MediumUrl = ExtractUrl(doc, ns, Constants.MediumImage),
                SmallUrl = ExtractUrl(doc, ns, Constants.SmallImage)
            };
        }
        private static string ExtractUrl(XDocument doc, XNamespace ns, string tag)
        {
            XElement item = doc.Root.Descendants(ns + tag).FirstOrDefault();
            if (item != null)
            {
                var url = item.Descendants(ns + Constants.Url).FirstOrDefault();
                if (url != null)
                {
                    return url.Value;
                }
            }
            return null;
        }
    }
}
